const app = getApp();

Page({
  data: {
    keyword: '',
    products: [],
    loading: false,
    page: 1,
    hasMore: true,
    history: []
  },

  onLoad(options) {
    if (options.keyword) {
      this.setData({ 
        keyword: options.keyword 
      }, () => {
        this.search();
      });
    }
    this.loadHistory();
  },

  loadHistory() {
    const history = wx.getStorageSync('searchHistory') || [];
    this.setData({ history });
  },

  saveHistory(keyword) {
    let history = wx.getStorageSync('searchHistory') || [];
    if (!history.includes(keyword)) {
      history.unshift(keyword);
      if (history.length > 10) {
        history.pop();
      }
      wx.setStorageSync('searchHistory', history);
      this.setData({ history });
    }
  },

  clearHistory() {
    wx.showModal({
      title: '提示',
      content: '确定要清空搜索历史吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('searchHistory');
          this.setData({ history: [] });
        }
      }
    });
  },

  handleInput(e) {
    this.setData({
      keyword: e.detail.value
    });
  },

  handleSearch() {
    const { keyword } = this.data;
    if (!keyword.trim()) {
      return;
    }
    this.saveHistory(keyword);
    this.setData({
      page: 1,
      products: [],
      hasMore: true
    }, () => {
      this.search();
    });
  },

  handleHistoryTap(e) {
    const { keyword } = e.currentTarget.dataset;
    this.setData({
      keyword,
      page: 1,
      products: [],
      hasMore: true
    }, () => {
      this.search();
    });
  },

  async search() {
    if (this.data.loading || !this.data.hasMore) return;

    this.setData({ loading: true });

    try {
      const res = await wx.request({
        url: `${app.globalData.baseUrl}/product/search/`,
        method: 'GET',
        data: {
          keyword: this.data.keyword,
          page: this.data.page,
          page_size: 10
        }
      });

      if (res.data.code === 200) {
        const { data, has_more } = res.data.data;
        this.setData({
          products: [...this.data.products, ...data],
          hasMore: has_more,
          page: this.data.page + 1
        });
      }
    } catch (error) {
      console.error('搜索失败', error);
    } finally {
      this.setData({ loading: false });
    }
  },

  handleProductTap(e) {
    const { id } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/product/detail/detail?id=${id}`
    });
  },

  onReachBottom() {
    if (this.data.keyword) {
      this.search();
    }
  }
}); 